/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JPlaySudoku.java
 *
 * Created on 8-set-2010, 11.22.01
 */
package jsudoku.graphics;

import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import jsudoku.Sudoku;
import jsudoku.SudokuFileManager;
import jsudoku.exception.InvalidSudokuException;

/**
 *
 * @author Paolo
 */
public class JPlaySudoku extends javax.swing.JFrame {

    private JSudoku sudoku;
    private JFileChooser choose;

    /** Creates new form JPlaySudoku */
    public JPlaySudoku() {
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (UnsupportedLookAndFeelException ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException ex1) {
            } catch (InstantiationException ex1) {
            } catch (IllegalAccessException ex1) {
            } catch (UnsupportedLookAndFeelException ex1) {
            }
        }
        initComponents();
        this.initFileChooser();
        this.sudoku = new JSudoku();
        this.add(this.sudoku);
    }

    public void initFileChooser() {
        this.choose = new JFileChooser();
        this.choose.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.getName().endsWith(".sdk") || f.isDirectory()) {
                    return true;
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "File sudoku (.sdk)";
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonPanel = new javax.swing.JPanel();
        newButton = new javax.swing.JButton();
        verifyButton = new javax.swing.JButton();
        stateLabel = new javax.swing.JLabel();
        state = new javax.swing.JLabel();
        createButton = new javax.swing.JButton();
        menu = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        open = new javax.swing.JMenuItem();
        save = new javax.swing.JMenuItem();
        exit = new javax.swing.JMenuItem();
        Info = new javax.swing.JMenu();
        help = new javax.swing.JMenuItem();
        info = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JSudoku - By Paolo Ricciuti (C)");
        setResizable(false);
        //BUG4
        //newButton.setText("Verifica"); //BUG4 end
        newButton.setText("Nuovo Sudoku");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
                
            }
        });
        //BUG4
        //verifyButton.setText("Nuovo Sudoku"); //BUG 4 end
        verifyButton.setText("Verifica");
        verifyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                verifyButtonActionPerformed(evt);
            }
        });

        stateLabel.setText("Stato del sudoku:");

        createButton.setText("Crea nuovo");
        createButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createButtonActionPerformed(evt);
                
            }
        });

        javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel);
        buttonPanel.setLayout(buttonPanelLayout);
        buttonPanelLayout.setHorizontalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buttonPanelLayout.createSequentialGroup()
                        .addComponent(stateLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(buttonPanelLayout.createSequentialGroup()
                        .addComponent(newButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(verifyButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(createButton)))
                .addContainerGap(17, Short.MAX_VALUE))
        );
        buttonPanelLayout.setVerticalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton)
                    .addComponent(verifyButton)
                    .addComponent(createButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stateLabel)
                    .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        file.setText("File");

        open.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        open.setText("Apri");
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        file.add(open);

        save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        save.setText("Salva");
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });
        file.add(save);

        exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        exit.setText("Esci");
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        file.add(exit);

        menu.add(file);

        Info.setText("?");

        help.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        help.setText("Help");
        help.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpActionPerformed(evt);
            }
        });
        Info.add(help);

        info.setText("Informazioni su JSudoku");
        info.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infoActionPerformed(evt);
            }
        });
        Info.add(info);

        menu.add(Info);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(303, Short.MAX_VALUE)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-316)/2, (screenSize.height-438)/2, 316, 438);
    }// </editor-fold>//GEN-END:initComponents

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        int retval = this.choose.showOpenDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            SudokuFileManager sfm = new SudokuFileManager(this.choose.getSelectedFile());
            try {
                Sudoku sud = sfm.openSudoku();
                this.sudoku.setSudoku(sud);
            } catch (FileNotFoundException ex) {
            } catch (IOException ex) {
            } catch (InvalidSudokuException ex) {
                JOptionPane.showMessageDialog(this, "File sudoku non valido.");
            }
        }
    }//GEN-LAST:event_openActionPerformed

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        this.sudoku.setSudoku(new Sudoku());
    }//GEN-LAST:event_newButtonActionPerformed

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        int confirm = JOptionPane.OK_OPTION;
        if (!this.sudoku.getSudoku().checkSudoku()) {
            confirm = JOptionPane.showConfirmDialog(this, "Il sudoku non è corretto, salvandolo non sarà più possibile modificarlo.\nContinuare?");
        }
        if (confirm == JOptionPane.OK_OPTION) {
            int retval = this.choose.showSaveDialog(this);
            if (retval == JFileChooser.APPROVE_OPTION) {
                SudokuFileManager sfm = new SudokuFileManager(this.choose.getSelectedFile());
                try {
                    sfm.saveSudoku(this.sudoku.getSudoku());
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(this, "Errore nel salvataggio file!");
                }
            }
        }
    }//GEN-LAST:event_saveActionPerformed

    private void verifyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_verifyButtonActionPerformed
        Sudoku sud = this.sudoku.getSudoku();
        String solved = "risolto";
        String correct = "corretto";
        if (!sud.checkSudoku()) {
            correct = "non " + correct;
        }
        if (!sud.isResolvedSudoku()) {
            solved = "non " + solved;
        }
        this.state.setText(solved + " - " + correct);
    }//GEN-LAST:event_verifyButtonActionPerformed

    private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
        int retval = JOptionPane.showConfirmDialog(this, "Confermando il gioco attuale verrà perso\n la griglia verrà svuotata per permettervi di creare un nuovo schema da salvare.");
        if (retval == JOptionPane.OK_OPTION) {
            this.sudoku.getSudoku().emptySudoku();
            this.sudoku.repaintSudoku();
            this.sudoku.initListeners();
        }
    }//GEN-LAST:event_createButtonActionPerformed

    private void helpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpActionPerformed
        JHelp helpWindow = new JHelp();
        helpWindow.setVisible(true);
    }//GEN-LAST:event_helpActionPerformed

    private void infoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoActionPerformed
        JFrame frame = new JFrame("Informazioni su JSudoku");
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setBounds(this.getLocation().x + 100, this.getLocation().y + 100, 400, 300);
        frame.setVisible(true);
        JLabel content = new JLabel();
        content.setIcon(new ImageIcon(getClass().getResource("/jsudoku/graphics/images/logo.png")));
        content.setText("<html>"
                + "Creato da Paolo Ricciuti senza alcun scopo di lucro per la "
                + "community PieroTofy a scopo illustrativo dei principali "
                + "metodi e classi del package swing."
                + "</html>");
        frame.add(content);
    }//GEN-LAST:event_infoActionPerformed
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JPlaySudoku().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu Info;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton createButton;
    private javax.swing.JMenuItem exit;
    private javax.swing.JMenu file;
    private javax.swing.JMenuItem help;
    private javax.swing.JMenuItem info;
    private javax.swing.JMenuBar menu;
    private javax.swing.JButton newButton;
    private javax.swing.JMenuItem open;
    private javax.swing.JMenuItem save;
    private javax.swing.JLabel state;
    private javax.swing.JLabel stateLabel;
    private javax.swing.JButton verifyButton;
    // End of variables declaration//GEN-END:variables
}
